# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from cStringIO import StringIO
import zipfile
from django import forms
from job_manager.models import FeedGroup, Feed, Feed
from job_manager.utils.logging_utils import getlogger

log = getlogger(__name__)

class UploadFeedForm(forms.ModelForm):
    file = forms.FileField()
    feed_group = forms.ModelChoiceField(queryset=FeedGroup.objects.all())

    class Meta:
        model = Feed
        fields = ('name', 'description')

    def cleaned_zipfile(self):
        zip_file = self.cleaned_data['file']
        if zip_file.content_type != 'application/zip':
#            msg = 'File upload must be a valid ZIP archive.'
#            raise forms.ValidationError(msg)
            log.debug("unknown content type: %s" % zip_file.content_type)
        else:
            try:
                zip = zipfile.ZipFile(zip_file.file)
            except:
                raise forms.ValidationError("Could not unzip file.")
            bad_file = zip.testzip()
            zip.close()
            del zip
            if bad_file:
                raise forms.ValidationError("Zip is bad!")
        return zip_file

class CreateFeedGroupForm(forms.ModelForm):
    class Meta:
        model = FeedGroup